<script lang='ts' setup>
import { openDialog } from './dialog/EditDataSourceDialog.vue'
import Refresh from '~icons/ep/refresh'
import Search from '~icons/ep/search'
import Add from '~icons/ep/plus'


const data = ref({
  list: [] as any[],
  totalElements: 0,
  pageNo: 1,
  pageSize: 12,
  totalPages: 1
});

onMounted(() => {
  handleLoadData()
})

const  value2key = {
  'DATABASE': '数据库'
}

async function handleLoadData(): Promise<void> {
  $request.get('/dataSource/page', { params: searchFormData }).then(res => {
    data.value = res.data as any
    if (data.value.totalElements == 0) {
      const { name, type } = searchFormData;
      const message = name || value2key[type || ''];
      emptyDescription.value =  message ? `没有查找到相关 '${message}' 的数据源` : '暂无数据，快去添加吧'
    }
   })
}

const emptyDescription = ref('')
const searchFormData = reactive({
  name: null,
  type: '',
  pageNo: 1,
  pageSize: 12
})

function handleSubmit():void {
  searchFormData.pageNo = 1;
  handleLoadData()
}

function handleReset():void {
  searchFormData.pageNo = 1;
  searchFormData.name = null;
  searchFormData.type = '';
  handleLoadData()
}

function handleCurrentChange(pageNo: number):void {
  searchFormData.pageNo = pageNo
  handleLoadData()
}


const { appContext } = getCurrentInstance()!

function handleTestDataSource(item: any):void {
  $request.post(`/dataSource/test/${item.id}`).then(() => {
    ElMessage({
    message: '数据库连接成功',
      type: 'success'
    });
  }).catch(err => {
    ElMessage({
      message: err?.response.data?.message || err?.message || '数据库连接失败',
      type: 'warning',
    });
  })

}
function handlEditDataSource(item: any):void {
  openDialog(item)
}

function handleDeleteDataSource(item: any):void {
  // 或者正在使用不同的调用方式
  ElMessageBox.confirm('此操作将永久删除该数据源, 是否继续?', '提示', {
  confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }, appContext).then(() => {
    $request.delete(`/dataSource/${item.id}`).then(() => {
      handleReset()
    })
  })
}


onMounted(() => {
  console.log(window.eventer)
  window.eventer.on('refresh:data-source', () => {
    handleReset()
  })
})


</script>

<template >
  <div >
    <div class="card-container" style="--query-header-height: 60px; --query-footer-height: 60px;">
      <div style="height: var(--query-header-height);width: 100%;" >
        <el-row style="height: 100%;" align="middle">
          <el-form size="" @keydown.enter="handleSubmit" :inline="true" label-width="90" :model="searchFormData" class="demo-form-inline">
          <el-form-item label="数据源名称" >
            <el-input v-model="searchFormData.name" placeholder="数据源名称" clearable />
          </el-form-item>
          <el-form-item label="数据源类型">
            <el-select
              v-model="searchFormData.type"
              placeholder="数据源类型"
              clearable
            >
              <el-option label="数据库" value="DATABASE" />
            </el-select>
          </el-form-item>
          <el-form-item style="margin-left: 10px;">
            <el-button type="primary"  :icon="Search" @click="handleSubmit">搜索</el-button>
            <el-button :icon="Refresh" @click="handleReset">重置</el-button>
            <el-button type="success" :icon="Add"  @click="handlEditDataSource(null)">新增</el-button>
          </el-form-item>
        </el-form>
        </el-row>
      </div>
      <br />
      <el-scrollbar style="width: 100%;" height="calc(--inner-window-height - 30px - 20px - var(--query-footer-height) - var(--query-header-height))">
        <el-row v-if="data.totalPages > 0" :gutter="24" style="margin-left: 0px;margin-right: 0px;">
        <el-col v-for="(item, index) in data.list" :key="index"
        :xs="12"
        :sm="12"
        :md="8"
        :lg="6"
        :xl="4"
        >
          <div class="card-item">
            <el-card style="max-width: 300px; --el-card-padding:10px;">
            <template #header>
              <div class="card-item_header">
                <el-icon size="30">
                  <IconDeviconAzuresqldatabase />
                </el-icon>
                <span class="__name" :title="item.name">  {{ item.name }}</span>
              </div>
            </template>
            <div class="card-item_description"  :title="item.description">
              <el-tooltip
                effect="dark"
                :content="item?.description"
              >
                <el-text line-clamp="2" size="small">
                        {{ item?.description }}
                      </el-text>
              </el-tooltip>
            </div>
            <template #footer>
              <div class="card-item_options">
                <el-button type="success" link @click="handleTestDataSource(item)">测试</el-button>
                <el-button type="primary" link @click="handlEditDataSource(item)">编辑</el-button>
                <el-button type="danger" link @click="handleDeleteDataSource(item)">删除</el-button>
              </div>
            </template>
          </el-card>
          </div>
        </el-col>
        </el-row>
        <el-empty v-else :description="emptyDescription" />
      </el-scrollbar>
      <div style="height: var(--query-footer-height);width: 100%;;display: flex; justify-content: flex-end; align-items: center;">
        <el-pagination
        v-if="data.totalPages > 1"
      background
      :current-page="data.pageNo"
      layout="total, prev, pager, next"
      :total="data.totalElements"
      @current-change="handleCurrentChange"
    />
      </div>
    </div>
  </div>
</template>

<style scoped lang='less'>
.card-container {
  display: flex;
  flex-wrap: wrap;
  .card-item {
    margin: 10px 0px;
    .card-item_header {
      display: flex;
      align-items: center;
      gap: 2px;
      .__name {
        font-size: 14px;
      }
    }
    .card-item_description {
      height: 40px;
      word-wrap:break-word;
      word-break:break-all;
    }
    .card-item_options {
      display: flex;
      justify-content: center;
      align-items: center;
      .el-button {
        flex: 1;
        border-right: 1px solid #eee;
        &:last-child {
          border-right: none;
        }
      }
    }
  }
}
:deep(.el-form-item) {
  margin-bottom: 10px;
  margin-right: 0px;
  .el-form-item__label {
    font-size: 12px;
  }
}
:deep(.el-select) {
  --el-select-width: 120px;
  .el-select__wrapper {
    font-size: 12px;
  }
}

:deep(.el-input) {
  --el-input-width: 120px;
  font-size: 12px;
}
</style>
